/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: AioClient
 * Author:   zengjian
 * Date:     2018/9/16 10:33
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package fun.codedesign.jdk.socket.aio;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * 〈Aio客户端〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/9/16 10:33
 */
public class AioClient {

    private AsynchronousSocketChannel channel;

    public AioClient() {
        try {
            channel = AsynchronousSocketChannel.open();
            channel.connect(new InetSocketAddress("localhost", 8080));
            System.out.println("channel连接上8080端口");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String sendMessage(String message) {
        final ByteBuffer byteBuffer = ByteBuffer.allocate(message.getBytes().length);
        byteBuffer.put(message.getBytes());
        byteBuffer.flip();
        channel.write(byteBuffer, byteBuffer, new WriteHandler(byteBuffer, channel));
        System.out.println("写入信息:" + message);
        ByteBuffer byteBuffer1 = ByteBuffer.allocate(1024);
        channel.read(byteBuffer1, byteBuffer1, new ReadHandler(byteBuffer1, channel));
        return "";
    }

    class WriteHandler implements CompletionHandler<Integer, ByteBuffer> {

        private ByteBuffer byteBuffer;
        private AsynchronousSocketChannel channel;

        public WriteHandler(ByteBuffer byteBuffer, AsynchronousSocketChannel channel) {
            this.byteBuffer = byteBuffer;
            this.channel = channel;
        }

        @Override
        public void completed(Integer result, ByteBuffer attachment) {
            System.out.println("发送消息成功");
            if (byteBuffer.hasRemaining()) {
                channel.write(attachment, attachment, this);
            }
        }

        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {
            System.out.println(exc);
        }
    }

    class ReadHandler implements CompletionHandler<Integer, ByteBuffer> {

        // private final ByteBuffer byteBuffer;
        // private final AsynchronousSocketChannel channel;

        public ReadHandler(ByteBuffer byteBuffer, AsynchronousSocketChannel channel) {
            // this.byteBuffer = byteBuffer;
            // this.channel = channel;
        }

        @Override
        public void completed(Integer result, ByteBuffer attachment) {
            attachment.flip();
            byte[] bytes = new byte[attachment.remaining()];
            attachment.get(bytes);
            try {
                System.out.println("接收服务器响应：" + new String(bytes, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {
            System.err.println(exc);
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        AioClient client = new AioClient();
        for (int i = 0; i < 10000; i++) {
            client.sendMessage("客户端请求(" + i + ")");
            Thread.sleep(1000);
        }
        System.in.read();
    }
}

